<template>
  <div class="bg-gray-50 min-h-screen">
    <!-- 顶部导航栏 -->
    <header class="bg-white border-b border-gray-200 sticky top-0 z-50">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between items-center h-16">
          <!-- Logo和身份标识 -->
          <div class="flex items-center gap-3">
            <div class="w-10 h-10 bg-blue-500 rounded-full overflow-hidden">
                <img src="../../../头像.jpg" alt="头像" class="w-full h-full object-cover" />
              </div>
            <span class="text-xl font-semibold text-gray-900">校园快递代拿</span>
            <span class="px-3 py-1 bg-blue-50 text-blue-600 text-sm rounded-full">代拿员</span>
          </div>

          <!-- 右侧按钮统一使用 HeaderActions -->
          <HeaderActions />
        </div>
      </div>
    </header>

    <!-- 标签页导航 -->
    <div class="bg-white border-b border-gray-200">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <nav class="flex gap-8">
          <button class="py-4 text-gray-600 hover:text-blue-600 border-b-2 border-transparent hover:border-blue-600" @click="$router.push('/courier/hall')">接单大厅</button>
          <button class="py-4 text-gray-600 hover:text-blue-600 border-b-2 border-transparent hover:border-blue-600" @click="$router.push('/courier/orders')">我的订单</button>
          <button :class="['py-4','border-b-2','font-medium', $route.path.startsWith('/courier/profile') ? 'text-blue-600 border-blue-600' : 'text-gray-600 border-transparent hover:border-blue-600']" @click="$router.push('/courier/profile')">我的主页</button>
        </nav>
      </div>
    </div>

    <!-- 主体 -->
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div class="flex gap-6">
        <!-- 左侧边栏（保持不变） -->
        <aside class="w-80 flex-shrink-0">
          <div class="bg-white rounded-2xl shadow-sm p-6 mb-6">
            <div class="flex flex-col items-center">
              <div class="relative mb-3">
                <img :key="avatarKey" :src="avatarUrl || '../../../头像.jpg'" alt="用户头像" class="w-24 h-24 rounded-full object-cover border border-gray-200">
                <button type="button" class="absolute bottom-0 right-0 bg-white/90 border border-gray-300 rounded-full px-2 py-0.5 text-xs text-gray-700 hover:bg-gray-50" @click="triggerAvatarSelect">更换</button>
              </div>
              <input ref="avatarInput" type="file" accept="image/*" class="hidden" @change="onAvatarChange" />
              <h2 class="text-xl font-semibold text-gray-900 mb-2">{{ profileName }}</h2>
              <span class="px-3 py-1 bg-blue-50 text-blue-600 text-sm rounded-full mb-6">代拿员</span>
              <div class="flex gap-8 w-full justify-center">
                <div class="text-center"><div class="text-2xl font-bold text-gray-900">{{ statistics.completedOrders || 0 }}</div><div class="text-sm text-gray-500 mt-1">已完成</div></div>
                <div class="text-center"><div class="text-2xl font-bold text-gray-900">{{ statistics.creditScore || 0 }}</div><div class="text-sm text-gray-500 mt-1">信用值</div></div>
                <div class="text-center"><div class="text-2xl font-bold text-gray-900">{{ statistics.inProgressOrders || 0 }}</div><div class="text-sm text-gray-500 mt-1">进行中</div></div>
              </div>
            </div>
          </div>

          <nav class="bg-white rounded-2xl shadow-sm overflow-hidden">
            <button :class="['flex items-center gap-3 px-6 py-4 w-full text-left', $route.path === '/courier/profile' ? 'text-blue-600 bg-blue-50 border-l-4 border-blue-600' : 'text-gray-600 hover:bg-gray-50 border-l-4 border-transparent']" @click="$router.push('/courier/profile')">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/></svg>
              个人信息
            </button>
            <button :class="['flex items-center gap-3 px-6 py-4 w-full text-left', $route.path === '/courier/profile/data' ? 'text-blue-600 bg-blue-50 border-l-4 border-blue-600' : 'text-gray-600 hover:bg-gray-50 border-l-4 border-transparent']" @click="$router.push('/courier/profile/data')">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"/></svg>
              服务数据
            </button>
            <button :class="['flex items-center gap-3 px-6 py-4 w-full text-left', $route.path === '/courier/profile/settings' ? 'text-blue-600 bg-blue-50 border-l-4 border-blue-600' : 'text-gray-600 hover:bg-gray-50 border-l-4 border-transparent']" @click="$router.push('/courier/profile/settings')">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/></svg>
              接单设置
            </button>
            <button :class="['flex items-center gap-3 px-6 py-4 w-full text-left', $route.path === '/courier/profile/wallet' ? 'text-blue-600 bg-blue-50 border-l-4 border-blue-600' : 'text-gray-600 hover:bg-gray-50 border-l-4 border-transparent']" @click="$router.push('/courier/profile/wallet')">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"/></svg>
              我的钱包
            </button>
            <button :class="['flex items-center gap-3 px-6 py-4 w-full text-left', $route.path === '/courier/profile/security' ? 'text-blue-600 bg-blue-50 border-l-4 border-blue-600' : 'text-gray-600 hover:bg-gray-50 border-l-4 border-transparent']" @click="$router.push('/courier/profile/security')">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"/></svg>
              账号安全
            </button>
            <button :class="['flex items-center gap-3 px-6 py-4 w-full text-left', $route.path === '/courier/profile/notify' ? 'text-blue-600 bg-blue-50 border-l-4 border-blue-600' : 'text-gray-600 hover:bg-gray-50 border-l-4 border-transparent']" @click="$router.push('/courier/profile/notify')">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"/></svg>
              通知设置
            </button>
            <button :class="['flex items-center gap-3 px-6 py-4 w-full text-left', $route.path === '/courier/profile/help' ? 'text-blue-600 bg-blue-50 border-l-4 border-blue-600' : 'text-gray-600 hover:bg-gray-50 border-l-4 border-transparent']" @click="$router.push('/courier/profile/help')">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
              帮助与反馈
            </button>
            <button class="flex items-center gap-3 px-6 py-4 text-red-600 hover:bg-red-50 border-l-4 border-transparent w-full text-left" @click="logout">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"/></svg>
              退出登录
            </button>
          </nav>
        </aside>

        <!-- 右侧内容区域（随路由变化） -->
        <main class="flex-1">
          <router-view />
        </main>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import HeaderActions from '../components/HeaderActions.vue'
export default {
  name: 'CourierProfileLayout',
  components: { HeaderActions },
  data() {
    return {
      profileName: '加载中...',
      avatarUrl: '',
      avatarKey: 0,
      statistics: {
        completedOrders: 0,
        creditScore: 100,
        inProgressOrders: 0
      }
    }
  },
  methods: {
    logout() {
      if (confirm('是否确认退出？')) {
        localStorage.removeItem('userToken')
        this.$router.push('/login')
      }
    },
    triggerAvatarSelect() {
      if (this.$refs.avatarInput) {
        this.$refs.avatarInput.value = ''
        this.$refs.avatarInput.click()
      }
    },
    async onAvatarChange(event) {
      const file = event.target.files && event.target.files[0]
      if (!file) return

      const userId = localStorage.getItem('userId')
      if (!userId) {
        alert('未登录，无法上传头像')
        return
      }

      try {
        const form = new FormData()
        form.append('file', file)

        const token = localStorage.getItem('userToken') || ''
        const uploadResp = await axios.post(`/api/upload/avatar?userId=${userId}`, form, {
          headers: {
            'Content-Type': 'multipart/form-data',
            ...(token ? { Authorization: `Bearer ${token}` } : {})
          }
        })

        const url = uploadResp.data && uploadResp.data.data && uploadResp.data.data.url
        if (!url) {
          alert('头像上传失败，请稍后重试')
          return
        }

        await axios.put(`/api/users/profile/${userId}`, { avatar_url: url })

        this.avatarUrl = url
        this.avatarKey = Date.now()
        localStorage.setItem('userAvatar', url)

        window.dispatchEvent(new CustomEvent('avatar-updated', { detail: { avatar_url: url } }))
        alert('头像更新成功')
      } catch (e) {
        console.error('头像上传或保存失败', e)
        alert('头像更新失败，请稍后再试')
      }
    },
    async loadProfile() {
      const userId = localStorage.getItem('userId')
      if (!userId) {
        this.profileName = '未登录用户'
        return
      }
      try {
        const { data } = await axios.get(`/api/users/profile/${userId}`)
        const root = (data && data.data) || {}
        const u = root.user || {}
        const cu = root.courier_user || {}

        this.profileName = u.nickname || (u.phone ? `用户${String(u.phone).slice(-4)}` : '代拿员')

        const apiAvatar = u.avatar_url || u.avatar
        const localAvatar = localStorage.getItem('userAvatar')
        const newAvatarUrl = apiAvatar || localAvatar || ''

        if (newAvatarUrl && newAvatarUrl !== this.avatarUrl) {
          this.avatarUrl = newAvatarUrl
          this.avatarKey = Date.now()
        }

        if (apiAvatar && apiAvatar !== localAvatar) {
          localStorage.setItem('userAvatar', apiAvatar)
        }

        this.statistics = {
          completedOrders: cu.completed_orders || 0,
          creditScore: (cu.credit_score !== undefined && cu.credit_score !== null)
            ? Number(cu.credit_score)
            : 100,
          inProgressOrders: cu.total_orders ? (cu.total_orders - (cu.completed_orders || 0)) : 0
        }
      } catch (e) {
        console.error('加载代拿员资料失败', e)
        this.profileName = '代拿员'
        const savedAvatar = localStorage.getItem('userAvatar') || ''
        if (savedAvatar) {
          this.avatarUrl = savedAvatar
          this.avatarKey = Date.now()
        }
      }
    }
  },
  mounted() {
    this.loadProfile()
  }
}
</script>
